<template>
  <div>
    <el-steps
      style="width: 100%; margin-bottom: 20px"
      :active="step"
      finish-status="success"
      align-center
    >
      <el-step title="基础配置" class="step-item" @click="changeStep(0)" />
      <el-step title="客服人员设置" class="step-item" @click="changeStep(1)" />
      <el-step title="欢迎语设置" class="step-item" @click="changeStep(2)" />
    </el-steps>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="120px">
      <el-form-item v-if="step === 0" prop="qrcodeName" label="渠道活码名称">
        <el-input
          v-model="form.qrcodeName"
          :disabled="type === 'detail'"
          autocomplete="off"
          clearable
        />
      </el-form-item>
      <el-form-item v-if="step === 0 && type !== 'add'" prop="state" label="添加渠道">
        <el-input
          v-model="form.state"
          disabled
          autocomplete="off"
          clearable
          placeholder="自定义state参数"
          maxlength="30"
          show-word-limit
        />
        <div class="tips"
          >自定义state参数，用于区分不同的添加渠道，在调用“获取客户详情时会返回该参数值，不超过30个字符”</div
        >
      </el-form-item>
      <el-form-item v-if="step === 1" prop="type" label="联系方式类型">
        <el-radio-group
          v-model="form.type"
          :disabled="type === 'detail'"
          @change="handleTypeChange"
        >
          <el-radio :label="1">单人</el-radio>
          <el-radio :label="2">多人</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="step === 1" prop="userList" label="客服人员">
        <el-select
          v-model="form.userList"
          :multiple="form.type === 2"
          :disabled="type === 'detail'"
          placeholder="请选择至少一个客服人员"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="(item, index) in userOptions"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="step === 0" prop="autoTag" label="自动打标签">
        <el-switch v-model="form.autoTag" :disabled="type === 'detail'" />
        <span class="ml-10px" v-text="form.autoTag ? '已启用' : '已关闭'"></span>
        <div class="tips">因为企业微信限制，标签存在延时，预计会在添加客户后的2分钟内生效</div>
      </el-form-item>
      <el-form-item v-if="step === 0 && form.autoTag" prop="tagList" label="客户标签">
        <el-select
          v-model="form.tagList"
          multiple
          :disabled="type === 'detail'"
          placeholder="请选择至少一个客户标签"
          style="width: 100%"
        >
          <el-option
            v-for="item in tagListOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="step === 0" prop="autoRemark" label="自动备注">
        <el-switch v-model="form.autoRemark" :disabled="type === 'detail'" />
        <span class="ml-10px" v-text="form.autoRemark ? '已启用' : '已关闭'"></span>
        <div class="tips">开启后可为客户昵称添加备注，方便查看用户来源</div>
      </el-form-item>
      <el-form-item v-if="step === 0 && form.autoRemark" prop="remarkContent" label="备注内容">
        <el-input v-model="form.remarkContent.label" :disabled="type === 'detail'" />
        <el-space class="mt-10px">
          <el-button @click="handleRemarkContent('nickname')">客户昵称</el-button>
          <el-button @click="handleRemarkContent('addTime')">添加时间</el-button>
        </el-space>
      </el-form-item>
      <el-form-item v-if="step === 0" prop="skipVerify" label="自动通过好友">
        <el-switch v-model="form.skipVerify" :disabled="type === 'detail'" />
        <span class="ml-10px" v-text="form.skipVerify ? '已启用' : '已关闭'"></span>
        <div class="tips">外部客户添加时是否无需验证</div>
      </el-form-item>
      <el-form-item v-if="step === 0" prop="status" label="状态">
        <el-switch v-model="form.status" :disabled="type === 'detail'" />
      </el-form-item>
      <el-form-item v-if="step === 2" prop="welcomeMsgReq.text.content" label="欢迎语">
        <el-input
          v-model="form.welcomeMsgReq.text.content"
          type="textarea"
          :rows="10"
          :disabled="type === 'detail'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="turnToList">取消</el-button>
        <el-button v-if="step > 0" type="primary" @click="changeStep(step - 1)">上一步</el-button>
        <el-button v-if="step < 2" type="primary" @click="changeStep(step + 1)">下一步</el-button>
        <el-button v-if="step === 2 && type === 'add'" type="primary" @click="submitForm(0)"
          >保存</el-button
        >
        <el-button v-if="type === 'edit'" type="primary" @click="submitForm(1)"
          >更新</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import * as ChannelQrcodeApi from './api'
import { useRouter, useRoute } from 'vue-router'

const emit = defineEmits(['close', 'save', 'update'])
const message = useMessage()
const router = useRouter()
const route = useRoute()
const visible = ref(false)
const loading = ref(false)
const step = ref(0)
const form = ref({
  qrcodeName: '',
  type: 2,
  state: '',
  status: true,
  skipVerify: true,
  autoTag: false,
  autoRemark: false,
  remarkContent: {
    label: '',
    format: '',
    addTime: ''
  },
  welcomeMsgReq: {
    text: {
      content: ''
    }
  },
  tagList: [],
  userList: []
})
const type = ref('add')
const formRef = ref()
const rules = ref({
  qrcodeName: [{ required: true, message: '请输入渠道活码名称', trigger: 'blur' }],
  userList: [{ required: true, message: '请选择客服人员', trigger: 'change' }],
  type: [{ required: true, message: '请选择联系方式类型', trigger: 'change' }],
  tagList: [{ required: true, message: '请选择客户标签', trigger: 'change' }],
  remarkContent: [
    {
      required: true,
      message: '请输入备注内容',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.value.autoRemark && !form.value.remarkContent.label) {
          callback(new Error('请输入备注内容'))
        }
        callback()
      }
    }
  ],
  welcomeMsg: [{ required: true, message: '请输入欢迎语内容', trigger: 'blur' }],
})
const userOptions = ref<string[]>([])
const tagListOptions = ref<{ label: string; value: string }[]>([])

// 获取客服人员
const getChannelQrcode = (id: string) => {
  return new Promise((resolve, reject) => {
    form.value = {
      qrcodeName: '',
      type: 2,
      state: '',
      status: true,
      skipVerify: true,
      autoTag: false,
      autoRemark: false,
      remarkContent: {
        label: '',
        format: '',
        addTime: ''
      },
      welcomeMsgReq: {
        text: {
          content: ''
        }
      },
      tagList: [],
      userList: []
    }
    ChannelQrcodeApi.getChannelQrcode(id)
      .then((res) => {
        form.value = res

        if (res.remarkContent) {
          form.value.remarkContent = JSON.parse(res.remarkContent)
          if (form.value.remarkContent.format) {
            // 编辑模式：如果有format字段，进行逆向转换
            reverseTransformRemarkContent()
          }
        }
        if (res.userList && res.userList instanceof Array && res.userList.length) {
          form.value.userList = res.userList.map((item) => {
            return item.userName
          })
        }
        if (res.welcomeMsg) {
          form.value.welcomeMsgReq = {
            text: {
              content: res.welcomeMsg
            },
            ...JSON.parse(res.welcomeMsg)
          }
        } else {
          form.value.welcomeMsgReq = {
            text: {
              content: ''
            }
          }
        }
        form.value.status = res.status === 1
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// 获取客服人员
const getFollowUserList = () => {
  return new Promise((resolve, reject) => {
    userOptions.value = []
    ChannelQrcodeApi.getFollowUserList()
      .then((res) => {
        if (res && res instanceof Array && res.length) {
          userOptions.value = res
        }
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// 获取新客标签列表
const getTagListOptions = () => {
  return new Promise((resolve, reject) => {
    tagListOptions.value = []
    ChannelQrcodeApi.getCorpTagList({})
      .then((res) => {
        const data = res.groups
        if (data) {
          const tagList = data.filter((item) => item.groupName === '新客')
          if (tagList.length) {
            tagListOptions.value = tagList[0].tag.map((item) => {
              return {
                label: item.name,
                value: item.name
              }
            })
          }
        }
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

const turnToList = () => {
  router.push({
    name: 'ChannelQrcode'
  })
}

const changeStep = (turn: number) => {
  console.log(turn, step.value)
  if (step.value === turn) return
  if (turn < step.value) {
    step.value = turn
    return
  }
  formRef.value.validate((valid: boolean) => {
    console.log(valid)
    if (valid) {
      step.value = turn
    }
  })
}

const open = (formType: string, id: string) => {
  visible.value = true
  type.value = formType
  if (formType === 'add') {
    form.value.skipVerify = true
    form.value.type = 2
    form.value.remarkContent = {
      label: '',
      format: '',
      addTime: ''
    }
    form.value.status = true
    form.value.welcomeMsgReq = {
      text: {
        content: ''
      }
    }
  } else {
    getChannelQrcode(id)
  }
  getTagListOptions()
  getFollowUserList()
}

// 转换备注内容
const transformRemarkContent = () => {
  return new Promise((resolve) => {
    const content = form.value.remarkContent.label
    if (!content) {
      resolve({ param0: '', format: '$param0' })
    }

    // 检查是否包含特殊标记
    if (!content.includes('[客户昵称]') && !content.includes('[添加时间]')) {
      resolve({ param0: content, format: '$param0' })
    }

    // 分割内容，提取参数
    const parts = content.split(/\[客户昵称\]|\[添加时间\]/)
    const markers = content.match(/\[客户昵称\]|\[添加时间\]/g) || []

    let format = ''
    let currentIndex = 0
    const result: any = {}

    // 构建参数和格式
    for (let i = 0; i < parts.length; i++) {
      if (parts[i] !== '') {
        result[`param${currentIndex}`] = parts[i]
        format += `$param${currentIndex}`
        currentIndex++
      }

      if (i < markers.length) {
        if (markers[i] === '[客户昵称]') {
          format += '$nickName'
        } else if (markers[i] === '[添加时间]') {
          format += '$addTime'
          result.addTime = 'yyyy-MM-dd'
        }
      }
    }

    resolve({ ...result, format })
  })
}

// 逆向转换备注内容
const reverseTransformRemarkContent = () => {
  const remarkContent = form.value.remarkContent
  if (!remarkContent.format) {
    return
  }

  let label = remarkContent.format

  // 动态替换所有参数，不限制参数数量
  const paramRegex = /\$param(\d+)/g
  label = label.replace(paramRegex, (match, paramIndex) => {
    const paramValue = remarkContent[`param${paramIndex}`] || ''
    return paramValue
  })

  // 替换特殊标记
  label = label.replace(/\$nickName/g, '[客户昵称]')
  label = label.replace(/\$addTime/g, '[添加时间]')

  form.value.remarkContent.label = label
}

const close = () => {
  visible.value = false
  emit('close')
}

const submitForm = async (type: number) => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true

      const remarkContent = await transformRemarkContent()
      let params = Object.assign({}, form.value, {
        remarkContent: JSON.stringify(remarkContent),
        userList: form.value.userList.map((item) => {
          return {
            userName: item
          }
        }),
        status: form.value.status ? 1 : 0
      })

      if (type) {
        ChannelQrcodeApi.updateChannelQrcode(params)
          .then(() => {
            loading.value = false
            message.success('更新成功')
            emit('update')
            visible.value = false
          })
          .catch(() => {
            loading.value = false
          })
      } else {
        ChannelQrcodeApi.createChannelQrcode(params)
          .then(() => {
            loading.value = false
            message.success('保存成功')
            emit('save')
            visible.value = false
          })
          .catch(() => {
            loading.value = false
          })
      }
    }
  })
}

const handleRemarkContent = (type: string) => {
  if (!form.value.remarkContent.label) {
    form.value.remarkContent.label = ''
  }
  if (type === 'nickname') {
    form.value.remarkContent.label += '[客户昵称]'
  } else if (type === 'addTime') {
    form.value.remarkContent.label += '[添加时间]'
  }
}

const handleTypeChange = () => {
  form.value.userList = []
}

watch(route.query, (newVal: any) => {
  if (newVal) {
    open(newVal.type || 'add', newVal.id || null)
  }
})

onMounted(() => {
  if (route.query) {
    open((route.query.type as string) || 'add', route.query.id as string)
  }
})

defineExpose({
  open,
  close
})
</script>

<style scoped lang="scss">
.tips {
  font-size: 12px;
  color: #999;
  display: block;
  width: 100%;
}
</style>
<style lang="scss">
.step-item {
  cursor: pointer;
}
</style>
